//
//  ViewController.m
//  audioConvert
//
//  Created by Vincent on 2017/2/25.
//  Copyright © 2017年 Vincent. All rights reserved.
//

#import "ViewController.h"
#import "ZLLRecordingView.h"
#import "ZLLVoiceTools.h"

@interface ViewController ()<AVAudioPlayerDelegate>

@property(nonatomic,strong)AVAudioPlayer *player;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIButton *btn = [UIButton new];
    btn.bounds = CGRectMake(0, 0, 100,40);
    btn.center = CGPointMake(self.view.center.x, self.view.bounds.size.height-50);
    btn.backgroundColor = [UIColor yellowColor];
    [btn setTitle:@"开始" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(buttonSender:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
}

-(void)buttonSender:(UIButton *)sender{
    sender.selected = !sender.selected;
    ZLLRecordingView *voiceV = [self.view viewWithTag:1000];
    
    if(sender.selected){
        
        [sender setTitle:@"结束" forState:UIControlStateNormal];
        
        voiceV = [ZLLRecordingView new];
        voiceV.tag = 1000;
        voiceV.bounds = CGRectMake(0, 0, 100, 200);
        voiceV.center = self.view.center;
        voiceV.backgroundColor = [UIColor purpleColor];
        [self.view addSubview:voiceV];
        
        
        NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        [voiceV recordVoiceWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/audio.wav",path]]];
    }
    else{
        
        [sender setTitle:@"开始" forState:UIControlStateNormal];
        
        [voiceV stopRecordingWithBlock:^(NSURL *aURL) {
            
            NSString *amr = [aURL.path stringByDeletingLastPathComponent];
            amr = [amr stringByAppendingPathComponent:@"test.amr"];
            
            [ZLLVoiceTools convertWavToAmr:aURL.path amrSavePath:amr];
            
            [self removeFileWithURL:aURL];
            
            self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:amr] error:nil];
            self.player.delegate = self;
            [self.player prepareToPlay];
            [self.player play];
            
        }];
        
        //移除语音视图（如果在停止录音里移除程序会崩，还未清楚原因。原因估计是在对象的方法中移除对象【让对象内存释放，但是该方法还没有执行完成，过一段时间执行就不会崩】）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            UIView *view = [self.view viewWithTag:1000];
            [view removeFromSuperview];
        });
    }
    
}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    
    if(flag){
        [self removeFileWithURL:player.url];
        NSLog(@"playing finish");
    }
}

-(void)removeFileWithURL:(NSURL *)aURL{
    
    NSFileManager *fMag = [NSFileManager defaultManager];
    [fMag removeItemAtPath:aURL.path error:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
